import { configureStore } from '@reduxjs/toolkit';
import { createStore as createGeppettoStore } from '@metacell/geppetto-meta-client/common';
import generalReducer from './slices/generalSlice';
import experimentsReducer from './slices/experimentsSlice';
import consoleReducer from './slices/consoleSlice';
import errorsReducer from './slices/errorsSlice';
import drawerReducer from './slices/drawerSlice';
import topbarReducer from './slices/topbarSlice';
import tutorialReducer from './slices/tutorialsSlice';
import notebookReducer from './slices/notebookSlice';
import plotMiddleware from './middleware/plotMiddleware';
import rulesMiddleware from './middleware/rulesOperationsMiddleware';
import customMiddleware from './middleware/customMiddleware';
import baseLayout from '../components/Layout/defaultLayout';
import componentMap from '../components/Layout/componentsMap';

// Create Geppetto store first
const geppettoStore = createGeppettoStore(
  {},
  {},
  [],
  { baseLayout, componentMap }
);

// Get Geppetto store state
const geppettoState = geppettoStore.getState();

// Configure our Redux store with Redux Toolkit
export const store = configureStore({
  reducer: {
    general: generalReducer,
    experiments: experimentsReducer,
    console: consoleReducer,
    errors: errorsReducer,
    drawer: drawerReducer,
    topbar: topbarReducer,
    tutorial: tutorialReducer,
    notebook: notebookReducer,
    // Merge Geppetto reducers if any
    ...(typeof geppettoState === 'object' ? {} : {}),
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: ['persist/PERSIST'],
      },
    }).concat(plotMiddleware, rulesMiddleware, customMiddleware),
});

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

// Export typed hooks for use in components
export { useAppDispatch, useAppSelector } from './hooks';

